/**
 * Copyright 2009 Henning Teek, Ingo Renner
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.googlecode.bricket.web.common;

import java.util.ArrayList;

import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.StringResourceModel;

import com.googlecode.bricket.web.BricketFeedbackPanel;
import com.googlecode.bricket.web.WicketApplication;

public class BricketPanel extends Panel {
	protected static final String BUTTON_ID = "item";
	
	private BricketFeedbackPanel feedback;
	
	private boolean initFinished;

	private ArrayList<BricketAjaxPanel> buttons = new ArrayList<BricketAjaxPanel>();

	private StringResourceModel headline;

	public BricketPanel(String id) {
		super(id);
	}
	
	public BricketPanel(String id, IModel<?> model) {
		super(id, model);
	}

	protected final void addButton(BricketAjaxPanel button) {
		buttons.add(button);
	}
	
	private final void addButtons() {
		add(new ListView<WebMarkupContainer>("buttons", buttons) {
			@Override
			protected void populateItem(ListItem<WebMarkupContainer> item) {
				item.add(item.getModelObject().setRenderBodyOnly(true));
			}
		}.setRenderBodyOnly(true).setVisible(!buttons.isEmpty()));
	}

	protected final void setHeadline(StringResourceModel stringResourceModel) {
		this.headline = stringResourceModel;
	}
	
	private final void addHeadline() {
		add(new Label("headline", headline).setVisible(this.headline != null));
	}

	@Override
	protected void onBeforeRender() {
		super.onBeforeRender();
		 if (!hasBeenRendered()) {
			 init();
		 }
	}

	private void init() {
		if (!initFinished) {
			addHeadline();
			addButtons();

			add(new WebMarkupContainer("content") {
				@Override
				public boolean isTransparentResolver() {
					return true;
				}
			});

			this.feedback = ((WicketApplication) getApplication()).getBricketFeedbackPanel(getPage());
		}
		initFinished = true;
	}

	public BricketFeedbackPanel getFeedback() {
		return feedback;
	}
}
